package com.base.cn.platform.os.controller.mobile.user.center.operation;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.exam.paper.ExamPaper;
import com.base.cn.platform.os.entity.exam.record.ExamRecord;
import com.base.cn.platform.os.entity.exam.record.UserScoreRanking;
import com.base.cn.platform.os.service.exam.record.ExamRecordService;
import com.base.cn.platform.os.service.exam.record.LoadStartExamService;
import com.base.cn.platform.os.service.upload.LoggerGenService;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * H5作业Controller
 */
@Controller
@RequestMapping("/mobile/uc/operation")
public class MobileOperationController extends MobileBaseController {

    @Autowired
    private ExamRecordService examRecordService;
    @Autowired
    private LoadStartExamService loadStartExamService;
    @Autowired
    private LoggerGenService loggerGenService;

    /**
     * 作业首页
     */
    @RequestMapping("/operationIndex")
    public String operationIndex(Model model, HttpServletRequest request) {
        Map<String, Object> condition = new HashMap<>();
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        condition.put("userId", userId);
        condition.put("useType", 2);
        condition.put("status", 2);
//        model.addAttribute("finishCount", examRecordService.getExamRecordCount(condition));
        model.addAttribute("finishCount", 0);
        condition.put("status", "");
//        model.addAttribute("taskCount", examRecordService.getExamRecordCount(condition));
        model.addAttribute("taskCount", 0);
        return resultPage("/user/center/operation/operation-index");
    }

    /***
     * 作业列表追加分页
     * @param model
     * @param request
     * @param condition
     * @param currentPage
     * @return
     */
    @RequestMapping("/ajax/operationIndex")
    public String ajaxOperationIndex(Model model,
                                     HttpServletRequest request,
                                     @RequestBody Map<String, Object> condition,
                                     @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        condition.put("userId", userId);
        condition.put("useType", 2);
        condition.put("examPaperData", true);
        condition.put("courseData", true);
        condition.put("classesData", true);
        Map<String, Object> dataMap = examRecordService.findUserTaskExamRecordListPage(condition, currentPage, 10);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/user/center/operation/ajax-operation-index");
    }


    /**
     * 作业详情
     */
    @RequestMapping("/operationInfo")
    public String operationInfo(Model model,
                                @RequestParam("taskId") BigDecimal taskId) {
        Map<String, Object> condition = new HashMap<>();
        condition.put("id", taskId);
        condition.put("examPaperData", true);
        condition.put("courseData", true);
        ExamRecord examRecord = examRecordService.findExamRecordById(condition);
        model.addAttribute("examRecord", examRecord);
        int stateType = 1;//默认超提交
        //最后提交时间
        String strUpdateTime = DateUtils.format(examRecord.getUpdateTime(), "yyyy-MM-dd HH:mm:ss");
        //试卷对象
        ExamPaper examPaper = examRecord.getExamPaper();
        if (ObjectUtils.isEmpty(examPaper.getEndTime())) {
            stateType = 2;//正常提交
        } else {
            //最晚提交时间
            String strEndTime = DateUtils.format(examPaper.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            //试卷最后提交时间
            Date updateTime = DateUtils.parseDate(strUpdateTime, "yyyy-MM-dd HH:mm:ss");
            //规定最晚提交时间
            Date endTime = DateUtils.parseDate(strEndTime, "yyyy-MM-dd HH:mm:ss");
            if (endTime.after(updateTime)) {
                stateType = 2;//正常提交
            }
        }
        model.addAttribute("stateType", stateType);
        return resultPage("/user/center/operation/operation-info");
    }

    /**
     * 同一份同学作业列表
     *
     * @param model
     * @param request
     * @param condition
     * @param currentPage
     * @return
     */
    @RequestMapping("/ajax/examRecord")
    public String ajaxExamRecord(Model model,
                                 HttpServletRequest request,
                                 @RequestBody Map<String, Object> condition,
                                 @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage) {

        condition.put("userData", true);
        condition.put("examPaperData", true);
        condition.put("useType", 2);
        condition.put("status", 2);//只查询已完成的
        Map<String, Object> dataMap = examRecordService.findExamRecordListPage(condition, currentPage, 10);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/user/center/operation/ajax-operation-info");
    }


    /**
     * 作业结果
     */
    @RequestMapping("/operationResult")
    public String operationResult(HttpServletRequest request, Model model, @RequestParam("taskId") BigDecimal taskId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> _condition = new HashMap<>();
        _condition.put("id", taskId);
        _condition.put("userId", userId);
        _condition.put("loreSetPointData", true);
        _condition.put("rightNumData", true);
        Map<String, Object> dataMap = loadStartExamService.loadExamRecord(_condition);
        if (ResultUtil.getSuccess(dataMap)) {
            model.addAttribute("examRecord", ResultUtil.getEntity(dataMap));
            Map<String, Object> cardMap = loadStartExamService.loadExamRecordCard(userId, taskId, 0);
            model.addAttribute("cardMap", cardMap);
        }
        Map<String, Object> condition = new HashMap<>();
        Map<String, Object> map = (Map) ResultUtil.getEntity(dataMap);
        condition.put("examId", map.get("examId"));
        List<UserScoreRanking> examRecordList = examRecordService.queryUserScoreRanking(condition);
        Map<BigDecimal, UserScoreRanking> collect = examRecordList.stream().collect(Collectors.toMap(e -> e.getUserId(), e -> e, (value1, value2) -> {
            return value2;
        }));
        if (ObjectUtils.isNotEmpty(collect)) {
            if (ObjectUtils.isNotEmpty(collect.get(userId))&&ObjectUtils.isNotEmpty(examRecordList.get(0))) {
                model.addAttribute("score", examRecordList.get(0).getUserScore() - collect.get(userId).getUserScore());
            }
        }
        return resultPage("/user/center/operation/operation-result");
    }


    /**
     * 查看解析
     *
     * @param examRecordId 考试记录ID
     * @return 操作页面
     */
    @RequestMapping("/lookTaskParsing")
    public String lookTaskParsing(HttpServletRequest request,
                                  Model model,
                                  @RequestParam("examRecordId") BigDecimal examRecordId,
                                  @RequestParam(value = "index", required = false, defaultValue = "0") int index) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> condition = new HashMap<>();
        condition.put("id", examRecordId);
        condition.put("userId", userId);
        Map<String, Object> dataMap = loadStartExamService.loadExamRecord(condition);
        if (ResultUtil.getSuccess(dataMap)) {
            model.addAttribute("examRecord", ResultUtil.getEntity(dataMap));
            Map<String, Object> entity = (Map<String, Object>) ResultUtil.getEntity(dataMap);
            int useType = Integer.parseInt(String.valueOf(entity.get("useType")));
            BigDecimal examId = new BigDecimal(String.valueOf(entity.get("examId")));
            int type = Integer.parseInt(String.valueOf(entity.get("type")));
            int status = Integer.parseInt(String.valueOf(entity.get("status")));
            if (useType == 1 && type == 1 && status == 1) {//生成试卷的访问日志
                loggerGenService.genGoodsPVUVLog(examId, ShopType.ORDER_SHOP_EXAM);
            }
        }
        model.addAttribute("questionIndex", index);
        return resultPage("/user/center/operation/look-task-parsing");
    }
}